import java.util.*;





public class Solution802DFS {
    public List<Integer> eventualSafeNodes(int[][] graph) {
        int length = graph.length;
        //未访问 0，已访问有环 11，已访问无环 12；
        int[] status = new int[length];
        List<Integer> anquanList = new ArrayList<>();
        //按下标顺序遍历节点
        for (int i = 0; i < length; ++i) {
            if (anquan(graph, status, i)) {
                anquanList.add(i);
            }
        }
        return anquanList;
    }
    //status == 12 ; 无环则为安全节点
    public boolean anquan(int[][] graph, int[] status, int curr) {
        if (status[curr] > 0) {
            return status[curr] == 12;
        }
        //将当前节点标记为已访问
        status[curr] = 11;
        //递归遍历x下标的所有下个节点,
        for (int next : graph[curr]) {
//            return anquan(graph, status, y);
            if (!anquan(graph, status, next)) {
                return false;
            }
        }
        status[curr] = 12;
        return true;
    }









    public static void main(String[] args) {
        System.out.println(
                new Solution802DFS()
                        .eventualSafeNodes(
                                new int[][]{{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}}
                        )
        );
////        System.out.println(
//                new Solution802()
//                        .eventualSafeNodesTopology(
//                                new int[][]{{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}}
//                        )
//        );
    }

    public List<Integer> eventualSafeNodesTopology(int[][] graph) {
        int n = graph.length;
        List<List<Integer>> rg = new ArrayList<List<Integer>>();
        for (int i = 0; i < n; ++i) {
            rg.add(new ArrayList<Integer>());
        }
        int[] inDeg = new int[n];
        for (int x = 0; x < n; ++x) {
            for (int y : graph[x]) {
                rg.get(y).add(x);
            }
            inDeg[x] = graph[x].length;
        }

        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < n; ++i) {
            if (inDeg[i] == 0) {
                queue.offer(i);
            }
        }
        while (!queue.isEmpty()) {
            int y = queue.poll();
            for (int x : rg.get(y)) {
                if (--inDeg[x] == 0) {
                    queue.offer(x);
                }
            }
        }

        List<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < n; ++i) {
            if (inDeg[i] == 0) {
                ans.add(i);
            }
        }
        return ans;
    }


}
